package com.norma.netty.study.netty.heartbeat;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.EventLoop;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangchaofeng
 * @date 2020/12/30
 * @description
 */
public class NettyHeartbeatClientHandler extends ChannelInboundHandlerAdapter {

    /**
     * 最大容忍未收到读写次数
     */
    private static final Integer MAX_UN_REC_TIMES = 2;

    /**
     * 当前累计未发生读写事件次数
     */
    public Integer unRecTimes = 0;

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent stateEvent = (IdleStateEvent) evt;
            if (stateEvent.state() == IdleState.READER_IDLE) {
                System.out.println("读事件空闲~");
            } else if (stateEvent.state() == IdleState.WRITER_IDLE) {
                System.out.println("写事件空闲~");
            } else if (stateEvent.state() == IdleState.ALL_IDLE) {
                System.out.println("读写事件空闲~");
            }

            if (unRecTimes < MAX_UN_REC_TIMES) {
                unRecTimes++;
            } else {
                System.out.println("-->关闭channel");
                ctx.channel().close();
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("-->channelInactive");
        EventLoop eventExecutors = ctx.channel().eventLoop();
        eventExecutors.schedule(() -> NettyHeartbeatClient.main(new String[0])
                , 2, TimeUnit.SECONDS);

    }
}
